package com.autoreassociate;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.provider.Settings;
import android.util.TypedValue;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnLongClickListener;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.ListView;
import android.widget.TabHost;
import android.widget.TabHost.OnTabChangeListener;
import android.widget.TextView;
import android.widget.ToggleButton;

import com.autoreassociate.receiver.ConnectionCheckReceiver;
import com.autoreassociate.service.CaLifeCycleService;
import com.autoreassociate.tool.ConnectionAssociateTool;


public class MainActivity extends Activity {


	protected static Activity mainActivity;
	
	protected static String SCREEN_LOG_FORMAT = "\n[%1$tF %1$tT]%2$s\n";
	
	protected static String DHCP_SHORT_INFO_FORMAT = "IP: %s%s%nInterval: %s%s%nWait time: %s";

	protected Button alarmSettingButton;
	protected TextView dhcpTextView;
	protected static TextView rssiStrengthTextView;
	
	protected static int[] toggleButtons = new int[] {R.id.alarmServiceButton1, R.id.alarmServiceButton2, R.id.alarmServiceButton3};
	
	protected Intent settingActivity;
	
	protected Intent alarmSettingActivity;

	protected static ConnectionAssociateTool connectionAssociateTool;

	/*
	static {
		
	}
	*/
	
	
	
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        //TODO
        mainActivity = this;
        SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(MainActivity.this);
        
        //connectionAssociateTool = ConnectionAssociateTool.getInstance(this, (ListView)findViewById(R.id.logView));
        //connectionAssociateTool = ConnectionAssociateTool.getInstance(this.getApplicationContext(), (ListView)findViewById(R.id.logView));
        
        // 부팅시 객체가 생성되었을 경우를 고려.
        connectionAssociateTool = ConnectionAssociateTool.getInstance();
        
        if (connectionAssociateTool == null) {
        	// app를 직접 실행한 경우.
        	// 서비스를 통해 생명주기 관리
        	this.startService(new Intent(this, CaLifeCycleService.class));
        	
        	//while (connectionAssociateTool == null) {
        		//connectionAssociateTool = ConnectionAssociateTool.getInstance();
        		connectionAssociateTool = ConnectionAssociateTool.getInstance(this.getApplicationContext());
        		//connectionAssociateTool = CaLifeCycleService.connectionAssociateTool;//ConnectionAssociateTool.getInstance();
        	//}
        	
        	
        }
        
        // 로그기록을 화면 표
        ListView logView = (ListView)findViewById(R.id.logView);
        logView.setAdapter(connectionAssociateTool.getMessageLogManager().getAdapter());

        alarmSettingButton = (Button)findViewById(R.id.settingTextView);
        alarmSettingButton.setOnClickListener(alarmSettingClickListener);
        
        dhcpTextView = (TextView)findViewById(R.id.dhcpInfoTextArea);
        rssiStrengthTextView = (TextView)findViewById(R.id.rssiStrengthTextArea);
        
        settingActivity = new Intent(this, SettingActivity.class);
        alarmSettingActivity = new Intent(this, AlarmSettingActivity.class);

        
        TabHost tabHost = (TabHost)findViewById(R.id.TabHost01);
        tabHost.setup();

        
        //LayoutInflater.from(this).inflate(R.layout.main, tabHost.getTabContentView(), true);

        tabHost.addTab(tabHost.newTabSpec("Log")
                         .setIndicator("Log")
                         .setContent(R.id.LinearLayout0102));
        tabHost.addTab(tabHost.newTabSpec("IP info")
                         .setIndicator("IP info")
                         .setContent(R.id.LinearLayout0101));
        
        tabHost.setOnTabChangedListener(tabHostOnTabChangeListener);
        
        // 핑전송 정보를 표시
        updateSettingText(AlarmSettingActivity.getStartSettingFromSelectedSetting(sharedPreferences));
        
//        LayoutInflater inflater = (LayoutInflater)this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        
//        tabHost.addTab(tabHost.newTabSpec("tab3")
//                .setIndicator(inflater.inflate(R.layout.tab_menu_layout01, null)).setContent(R.id.LinearLayout0102)
//                );
        
        for ( int tab = 0; tab < tabHost.getTabWidget().getChildCount(); ++tab )
        {
        	tabHost.getTabWidget().getChildAt(tab).getLayoutParams().height = 50;
        }	

        
        
        tabHost.setCurrentTab(0);

        
        Button reassocateButton = (Button)findViewById(R.id.reassociateButton);
        reassocateButton.setOnClickListener(reassociteClickListener);
        
        Button clearButton = (Button)findViewById(R.id.clearButton);
        clearButton.setOnClickListener(clearClickListener);
        
        Button settingButton = (Button)findViewById(R.id.settingButton);
        settingButton.setOnClickListener(settingClickListener);
        
        Button exitButton = (Button)findViewById(R.id.exitButton);
        exitButton.setOnClickListener(exitClickListener);
        

        ToggleButton wifiOnOffButton = (ToggleButton)findViewById(R.id.wifiOnOffButton);
        wifiOnOffButton.setOnCheckedChangeListener(wifiOnOffCheckedChangeListener);
        wifiOnOffButton.setOnLongClickListener(wifiOnOffLongClickListener);
        
        connectionAssociateTool.restartWifiStatusReceiver();
        
        connectionAssociateTool.getMessageLogManager().printV(R.string.tooltip_start_01, android.R.drawable.ic_btn_speak_now);

        

        
        // 버전정보 표시 
        //versionInfo();

    }
    

    @Override
    protected void onResume() {
    	
    	super.onResume();
    	//TODO
    	//connectionAssociateTool = ConnectionAssociateTool.getInstance();
    	rssiStrengthTextView.setVisibility(View.GONE);
    	
    	ConnectionAssociateTool connectionAssociateTool = ConnectionAssociateTool.getInstance();
    	
    	int lastUseButtonId = connectionAssociateTool.getSharedPreferences().getInt(AlarmSettingActivity.LAST_USE_BUTTON_ID, 0);
    	ToggleButton alarmButton = null;
    	
        for (int toggleButton : toggleButtons) {
            alarmButton = (ToggleButton)findViewById(toggleButton);

            alarmButton.setOnCheckedChangeListener(alarmCheckedChangeListener);
            alarmButton.setOnLongClickListener(alarmLongClickListener);
            
            if (toggleButton == lastUseButtonId) {

            	alarmButton.setChecked(connectionAssociateTool.isRunningAlarm());
            }
            
        }
        
        toggleWifiOnOffButton();
    }
    
    /**
     * wifi버튼의 토글상태를 갱신
     */
    public static void toggleWifiOnOffButton() {
        ToggleButton wifiOnOffButton = (ToggleButton)mainActivity.findViewById(R.id.wifiOnOffButton);
        
        if (ConnectionAssociateTool.getInstance().getWifiManager().isWifiEnabled()) {
        	wifiOnOffButton.setChecked(true);
        } else {
        	wifiOnOffButton.setChecked(false);
        }
    }
    
    
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {

		super.onActivityResult(requestCode, resultCode, data);
	}

	
	@Override
	protected void onDestroy() {
		super.onDestroy();
		//connectionAssociateTool.instanceClose();
	}

	@Override
	protected void finalize() throws Throwable {
        super.finalize();        
        //connectionAssociateTool.instanceClose();
	}
	
	
    //-----------------------------------------------------------------------------------------
    protected OnClickListener reassociteClickListener = new OnClickListener() {
        public void onClick(View v) {
        	sendOrderedBroadcast(ConnectionCheckReceiver.REASSOCIATE_INTENT, null);
        }
    };
    
    
    protected OnClickListener clearClickListener = new OnClickListener() {
        public void onClick(View v) {
        	ConnectionAssociateTool.getInstance().getMessageLogManager().clearViewListLog();
        }
    };

    protected OnClickListener settingClickListener = new OnClickListener() {
        public void onClick(View v) {
        	startActivity(settingActivity);
        	
        }
    };
    
    protected OnClickListener exitClickListener = new OnClickListener() {
        public void onClick(View v) {
    	if (ConnectionAssociateTool.getInstance() != null) {
    			ConnectionAssociateTool.getInstance().instanceClose();
        	}
        	MainActivity.this.finish();
        }
    };
    
    protected OnCheckedChangeListener alarmCheckedChangeListener = new OnCheckedChangeListener() {


		public void onCheckedChanged(CompoundButton buttonView,
				boolean isChecked) {
			
			ConnectionAssociateTool connectionAssociateTool = ConnectionAssociateTool.getInstance();
	    	
			SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(MainActivity.this);
			
			if (isChecked) {
				
				for (int toggleButtons : MainActivity.toggleButtons) {
					ToggleButton alarmButton = (ToggleButton)findViewById(toggleButtons);

					if(!buttonView.equals(alarmButton)) {
						alarmButton.setChecked(false);
					}
				}
				
				// Object[] {pingSendInterval, pingWaitingTime, pingIpAddressCustomSet, pingSendIpAddress};
				Object[] result = AlarmSettingActivity.setStartSettingFromButtonSetting(sharedPreferences, buttonView.getId());
				updateSettingText(result);
				
				connectionAssociateTool.startAlarm();

			} else {
				connectionAssociateTool.endAlarm();

			}
			
		}

    };
    
    
    protected OnClickListener alarmSettingClickListener = new OnClickListener() {

		public void onClick(View v) {

			//SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(MainActivity.this);

			//AlarmSettingActivity.setStartSettingFromButtonSetting(sharedPreferences, v.getId());
			int lastUseButtonId = ConnectionAssociateTool.getInstance().getSharedPreferences().getInt(AlarmSettingActivity.LAST_USE_BUTTON_ID, 0);
			alarmSettingActivity.putExtra(AlarmSettingActivity.BUTTON_NUMBER, lastUseButtonId);
			startActivity(alarmSettingActivity);

		}
	};
    
    protected OnLongClickListener alarmLongClickListener = new OnLongClickListener() {
    	
		public boolean onLongClick(View v) {

			for (int toggleButtons : MainActivity.toggleButtons) {
				ToggleButton alarmButton = (ToggleButton)findViewById(toggleButtons);
				alarmButton.setChecked(false);
			}
			
			SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(MainActivity.this);

			AlarmSettingActivity.setStartSettingFromButtonSetting(sharedPreferences, v.getId());
			
			alarmSettingActivity.putExtra(AlarmSettingActivity.BUTTON_NUMBER, v.getId());
			startActivity(alarmSettingActivity);
			return false;
		}
	};
    
    
	
	
    protected OnCheckedChangeListener wifiOnOffCheckedChangeListener = new OnCheckedChangeListener() {
    	public void onCheckedChanged(CompoundButton buttonView,
    			boolean isChecked) {

    		ConnectionAssociateTool connectionAssociateTool = ConnectionAssociateTool.getInstance();
        	
    		if (isChecked) {
    			connectionAssociateTool.getWifiManager().setWifiEnabled(true);
    		} else {
    			connectionAssociateTool.getWifiManager().setWifiEnabled(false);
    		}
    	}
    };
	
	
    protected OnLongClickListener wifiOnOffLongClickListener = new OnLongClickListener() {
    	
		public boolean onLongClick(View v) {

			startActivity(new Intent(Settings.ACTION_WIFI_SETTINGS));
			return false;
		}
	};
	
	
	
	protected OnTabChangeListener tabHostOnTabChangeListener = new OnTabChangeListener() {

		public void onTabChanged(String tabId) {
			if ("IP info".equals(tabId)) {
				// Ip정보탭의 내용 갱신
				dhcpTextView.setText(ConnectionAssociateTool.getInstance().getDhcpInfo());
			}	
		}	
	};
	
	
	
	
	public void updateSettingText(Object[] value) {
		// Object[] {pingSendInterval, pingWaitingTime, pingIpAddressCustomSet, pingSendIpAddress, isAlarmRtcWakeup};
		
		alarmSettingButton.setText(String.format(DHCP_SHORT_INFO_FORMAT, (Boolean)value[2] ? "M" : "A", value[3], (Boolean)value[4] ? "RW" : "R", value[0], value[1]));
	}
	

	public static void updateRssiStrengthText(CharSequence text) {
		
		if (text != null) {
			rssiStrengthTextView.setVisibility(View.VISIBLE);
		}
		
		rssiStrengthTextView.setText(text);
	}
	
	
    public void versionInfo() {
    	SharedPreferences pref = getSharedPreferences("VER", 0);

    	try{
    		PackageManager pm = this.getPackageManager();
    		PackageInfo packageInfo = pm.getPackageInfo(getPackageName(), 0);
    		int VERSION = packageInfo.versionCode;
    		int old_Ver = pref.getInt("version", 0);
    		
    		if(old_Ver<VERSION){
    			TextView msg=new TextView(this);
    			msg.setTextSize(TypedValue.COMPLEX_UNIT_SP,15);
    			msg.setTextColor(0xffffffff);
    			msg.setText(R.string.updateInfo);
    			new AlertDialog.Builder(this)
    			.setTitle(R.string.updateInfoTitel)
    			.setView(msg)	    		
    			.setPositiveButton("CLOSE", null)
    			.show();
    			
    			SharedPreferences.Editor edit = pref.edit();
    			edit.putInt("version",  VERSION);
    			edit.commit();
    		}
    	}
    	catch(Exception e){}
    }
	
    
    public static void pattenButtonToggle() {
    	
    	ConnectionAssociateTool connectionAssociateTool = ConnectionAssociateTool.getInstance();
    	
    	int lastUseButtonId = connectionAssociateTool.getSharedPreferences().getInt(AlarmSettingActivity.LAST_USE_BUTTON_ID, 0);

   	    ToggleButton alarmButton = (ToggleButton)mainActivity.findViewById(lastUseButtonId);
   
   	    if (alarmButton == null) {
   	    	alarmButton = (ToggleButton)mainActivity.findViewById(R.id.alarmServiceButton1);
   	    }
   	    
        alarmButton.setChecked(connectionAssociateTool.isRunningAlarm());
        
    }
    
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
    	if (KeyEvent.KEYCODE_BACK == keyCode) {
    		//this.onKeyDown(KeyEvent.KEYCODE_HOME, new KeyEvent(event.getAction(), KeyEvent.KEYCODE_HOME));
    		return false;
    	}
    	
    	return super.onKeyDown(keyCode, event);
    }

    
//------------------------------------------------------------------------



	/*
	 * 2010/07/23 : wifi on/off 와 rssi신호강도에 따른 연결 해제 기능 추가.
	 * 2010/07/28 : 영문 로케이션 수정. (keechang.kim@googlemail.com 감사)
	 *              Notification 아이콘 통합. (keechang.kim@googlemail.com 제안)
	 * 2011/01/10 : 이것저것 추가 ^^      
	 * 2011/01/12 : AlertSettingActivity에서 super.onPause(); 위치수정       
	 */
	
}